//
//  BGAuctionAddPriceController.m
//  bigMall
//
//  Created by LTOVE on 16/9/23.
//  Copyright © 2016年 thinklev. All rights reserved.
//

#import "BGAuctionAddPriceController.h"

#import "LTOVEDynamicCreakButton.h"
#import "BGDateResult.h"
#import "BGBeforeAuctionModel.h"
#import "BGLoginViewController.h"
#import "MJExtension.h"
#import "BGAddAuctionLogModel.h"
#import "BGCalculateMarginModel.h"
@interface BGAuctionAddPriceControllerAddBtnParam : NSObject
@property (nonatomic,copy)NSString *auctionId;
@property (nonatomic,copy)NSString *payPassword;
@property (nonatomic,copy)NSString *margin;
@property (nonatomic,copy)NSString *price;

@end
@interface BGAuctionAddPriceController ()<UITextFieldDelegate,dynamicButtonDelegate>{
    
    BOOL ispop;
    BOOL isMagins;
}
@property (nonatomic,strong)BGAuctionAddPriceControllerAddBtnParam *param;
@property (nonatomic,weak)BGBeforeAuctionModel *resultModel;
@property (nonatomic,copy)NSString *magin;
@end
@implementation BGAuctionAddPriceControllerAddBtnParam
#pragma mark -- 默认保证金和支付密码在这里赋值
- (NSString *)payPassword
{
    if (!_payPassword) {
        return @"";
    }else{
        return _payPassword;
    }
}

- (NSString *)margin
{
    if (!_margin) {
        return @"0.00";
    }else {
        return _margin;
    }
}
@end

@implementation BGAuctionAddPriceController



- (BGAuctionAddPriceControllerAddBtnParam *)param
{
    if (!_param) {
        _param = [BGAuctionAddPriceControllerAddBtnParam new];
        _param.auctionId = self.isMagin;
    }
    return _param;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = lightwhite_;
    
    // Do any additional setup after loading the view.
}
- (instancetype)init
{
    if (self = [super init]) {
        ispop = NO;
    }
    return self;
}
- (void)setIsMagin:(NSString *)isMagin
{
    _isMagin = isMagin;
    [BGDateResult beforeAuctionWithAuctionId:isMagin success:^(NSObject *result) {
        
        BGBeforeAuctionModel *model = (BGBeforeAuctionModel *)result;
        GWLog(@"%@",model.is_margin);
        self.resultModel = model;
        if (model.this_price) {
            [self calculateMaginWithMoney:model.this_price];
        }
        if ([model.status isEqualToString:@"-2"]) {
            
            UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:@"需要登录" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                NSMutableArray *aaaa = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
//                [aaaa removeLastObject];
//                self.navigationController.viewControllers = aaaa;
                BGLoginViewController *vc = [BGLoginViewController new];
                [self.navigationController pushViewController:vc animated:YES];
            }];
            [alertVc addAction:sure];
            [self presentViewController:alertVc animated:YES completion:^{
                
                
            }];
            
            
        }else if ([model.is_margin isEqualToString:@"0"]) {
            [self setUpAllSubViewsWithIsMagin:NO];
        }else{
            [self setUpAllSubViewsWithIsMagin:YES];
        }
        
    } failure:^(NSError *error) {
        
        
    }];
    
    
    
//    [self setUpAllSubViewsWithIsMagin:isMagin];
}

- (void)calculateMaginWithMoney:(NSString *)money
{
    [BGDateResult calculateMarginWithRole:@"buyer" type:@"auction" money:money objId:self.isMagin success:^(NSObject *result) {
        
        BGCalculateMarginModel *model = (BGCalculateMarginModel *)result;
//        self.resultModel.magin = model.margin;
        self.magin = model.margin;
        
    } failure:^(NSError *error) {
        
        
    }];
}

-(void)viewWillAppear:(BOOL)animated
{
    if (!ispop) {
        return;
    }
    for (UIView *view in self.view.subviews) {
        [view removeFromSuperview];
    }
    [BGDateResult beforeAuctionWithAuctionId:self.isMagin success:^(NSObject *result) {
        
        BGBeforeAuctionModel *model = (BGBeforeAuctionModel *)result;
        GWLog(@"%@",model.is_margin);
        self.resultModel = model;
        if (model.this_price) {
            [self calculateMaginWithMoney:model.this_price];
        }
        if ([model.status isEqualToString:@"-2"]) {
            
            UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:@"需要登录" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //                NSMutableArray *aaaa = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
                //                [aaaa removeLastObject];
                //                self.navigationController.viewControllers = aaaa;
                BGLoginViewController *vc = [BGLoginViewController new];
                [self.navigationController pushViewController:vc animated:YES];
            }];
            [alertVc addAction:sure];
            [self presentViewController:alertVc animated:YES completion:^{
                
                
            }];
            
            
        }
        if ([model.is_margin isEqualToString:@"0"]) {
            [self setUpAllSubViewsWithIsMagin:NO];
        }else{
            [self setUpAllSubViewsWithIsMagin:YES];
        }
    } failure:^(NSError *error) {
        
        
    }];
}
- (void)viewWillDisappear:(BOOL)animated
{
    NSArray *consArray = self.navigationController.viewControllers;
    if (consArray[consArray.count -2] == self) {
        ispop = YES;
    }
}
#pragma mark - 初始化视图
- (void)setUpAllSubViewsWithIsMagin:(BOOL)isMagin
{
    //
    isMagins = isMagin;
   
    UIView *viewNowPrice = [self viewWithTitle:@"当前报价:" isPassWord:NO andplaceholder:@"请输入出价金额" andtextFildTag:2 textFildStr:[NSString stringWithFormat:@"%@元",self.resultModel.max_amoutn]];
        viewNowPrice.y = 64;
        [self.view addSubview:viewNowPrice];
    
        //保证金  tag = 1
#pragma mark - 保证金需要接口计算
        UIView *maginView = [self viewWithTitle:@"最低加价金额:" isPassWord:NO andplaceholder:@"这里的是需要计算的 等待接口" andtextFildTag:1 textFildStr:[NSString stringWithFormat:@"%@元",self.resultModel.least_add]];
        maginView.y = CGRectGetMaxY(viewNowPrice.frame);
        [self.view addSubview:maginView];
        //出价金额  tag = 2
        UIView *priceView = [self viewWithTitle:@"保证金:" isPassWord:NO andplaceholder:@"请输入出价金额" andtextFildTag:2 textFildStr:[NSString stringWithFormat:@"%@元",self.magin]];
    UILabel *label = [UILabel new];
    label.center = self.view.center;
    label.text = self.magin;
    label.font = Font22;
    [label sizeToFit];
    [self.view addSubview:label];
        priceView.y = CGRectGetMaxY(maginView.frame);
        if (isMagin) {
            priceView.height = 0;
            priceView.hidden = isMagin;
        }
        [self.view addSubview:priceView];
        //密码    tag = 3
        UIView *passWordView = [self viewWithTitle:@"出价金额:" isPassWord:YES andplaceholder:@"请输入支付密码" andtextFildTag:3 textFildStr:[NSString stringWithFormat:@"%@元",self.resultModel.this_price]];
        passWordView.y = CGRectGetMaxY(priceView.frame);
        [self.view addSubview:passWordView];
    
    
    
    
    
    
    
    
    
    
    NSDictionary *dic = @{
                          NSFontAttributeName:Font34,
                          NSForegroundColorAttributeName:lightwhite_
                          };
    CGFloat btnH = 60;
    LTOVEDynamicCreakButton *view = [LTOVEDynamicCreakButton buttonViewWithFrame:CGRectMake(0, screenH - btnH, screenW, btnH) titleDataArray:@[@"出价"] andEdgInset:UIEdgeInsetsMake(5, 10, 5, 10) andMaginX:0 andMaginY:0 andBtnHeigh:btnH - 10 andBtnNorColor:read_ andBtnHeighColor:read_ andRadius:5 andFont:dic];
    view.delegate = self;
    [self.view addSubview:view];
    
}
#pragma mark - 出价按钮
- (void)dynamicButtonClick:(UIButton *)btn
{
    GWLog(@"%@",btn.titleLabel.text);
    
    GWLog(@"%@",self.param.keyValues);
    if (isMagins) {
        [self requestAddPriceApi];
    }else{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入支付密码" preferredStyle:UIAlertControllerStyleAlert];
    [alertVc addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
       textField.placeholder = @"请输入支付密码";
        textField.secureTextEntry = YES;
    }];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        UITextField *textFild = [alertVc.textFields firstObject];
        self.param.payPassword = textFild.text;
        GWLog(@"%@",self.param.keyValues);
#pragma mark - 这里请求出价接口

        [self requestAddPriceApi];
    }];
    [alertVc addAction:sure];
    [self presentViewController:alertVc animated:YES completion:^{
        
        
    }];
    }
    
}
#pragma mark - 这里请求出价接口
/**
 *  请求出价接口
 */
- (void)requestAddPriceApi
{
    [BGDateResult addAuctionLogWithAuvtionId:self.param.keyValues success:^(NSObject *result) {
        BGAddAuctionLogModel *model = (BGAddAuctionLogModel *)result;
        GWLog(@"%@",model.msg);
    } failure:^(NSError *error) {
        
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (UIView *)viewWithTitle:(NSString *)title isPassWord:(BOOL)isPassWord andplaceholder:(NSString *)placeholder andtextFildTag:(NSInteger)tag textFildStr:(NSString *)textFildStr
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenW, 45)];
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = title;
    titleLabel.font = Font34;
    titleLabel.textColor = textBlackColor;
    [titleLabel sizeToFit];
    titleLabel.x = BGMaginLeft;
    titleLabel.centerY = view.height * 0.5;
    [view addSubview:titleLabel];
//    UITextField *textFild = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(titleLabel.frame) + 5, titleLabel.y, screenW - 2 * BGMaginLeft - titleLabel.width, titleLabel.height)];
//    textFild.secureTextEntry = isPassWord;
    UITextField *textFild = [UITextField new];
    textFild.userInteractionEnabled = isPassWord;
    
    textFild.placeholder = placeholder;
    textFild.tag = tag;
    textFild.textColor = read_;
    textFild.text = textFildStr;
    textFild.font = Font30;
    [textFild sizeToFit];
    textFild.x = CGRectGetMaxX(titleLabel.frame) + 5;
    textFild.centerY = titleLabel.centerY;
    textFild.keyboardType = UIKeyboardTypeDecimalPad;
    textFild.delegate = self;
    [view addSubview:textFild];
//    CGSize textFiledSize = [textFild.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:textFild.font,UIFontDescriptorSizeAttribute, nil]];
    return view;
}
#pragma mark - 文本域文字改变
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    GWLog(@"%ld",(long)textField.tag);
    switch (textField.tag) {
        case 1:
            {
                CGFloat value = [textField.text floatValue];
                self.param.margin = [NSString stringWithFormat:@"%.2f",value];
            }
            
            break;
        case 2:
            {
                CGFloat value = [textField.text floatValue];
                self.param.price = [NSString stringWithFormat:@"%.2f",value];
            }
//            self.param.price = textField.text;
            break;
        case 3:
            {
                CGFloat value = [textField.text floatValue];
                self.param.payPassword = [NSString stringWithFormat:@"%.2f",value];
            }
//            self.param.payPassword = textField.text;
            break;
            
        default:
            break;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
